<template>
  <div class="role-manage-container">
    <div class="header-actions">
      <el-button type="primary" v-permission="'role:add'" @click="handleAdd"
        >新增角色</el-button
      >
    </div>

    <!-- 角色列表 -->
    <el-table :data="roleList" border stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="roleName" label="角色名称" width="150" />
      <el-table-column prop="roleCode" label="角色编码" width="120" />
      <el-table-column prop="description" label="角色描述" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="scope">
          <el-button
            v-permission="'role:edit'"
            type="primary"
            size="small"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            v-permission="'permission:assign'"
            type="success"
            size="small"
            @click="handleAssignPermission(scope.row)"
          >
            分配权限
          </el-button>
          <el-popconfirm
            title="确定删除该角色吗？"
            @confirm="handleDelete(scope.row.id)"
          >
            <template #reference>
              <el-button v-permission="'role:delete'" type="danger" size="small"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑角色' : '新增角色'"
      width="500px"
    >
      <el-form
        :model="roleForm"
        :rules="rules"
        ref="roleFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="roleForm.roleCode" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限分配对话框 -->
    <el-dialog v-model="permissionDialogVisible" title="分配权限" width="600px">
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTree"
        :props="{ label: 'permissionName', children: 'children' }"
        show-checkbox
        node-key="id"
        default-expand-all
        check-strictly
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPermission">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getRoleList,
  getRoleById,
  addRole,
  updateRole,
  deleteRole,
  getRolePermissions,
  assignRolePermissions
} from '@/api/role'
import { getPermissionTree } from '@/api/permission'

// 角色列表
const roleList = ref([])
// 权限树
const permissionTree = ref([])
// 对话框显示状态
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
// 是否为编辑模式
const isEdit = ref(false)
// 当前操作的角色ID
const currentRoleId = ref(null)
// 表单引用
const roleFormRef = ref(null)
const permissionTreeRef = ref(null)

// 角色表单
const roleForm = reactive({
  id: null,
  roleName: '',
  roleCode: '',
  description: '',
  status: 1
})

// 表单验证规则
const rules = {
  roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  roleCode: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 初始化
onMounted(() => {
  fetchRoleList()
})

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const res = await getRoleList()
    roleList.value = res.data.data || []
  } catch (error) {
    console.error('获取角色列表失败', error)
    ElMessage.error('获取角色列表失败')
  }
}

// 新增角色
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = async (row) => {
  isEdit.value = true
  resetForm()
  try {
    const res = await getRoleById(row.id)
    Object.assign(roleForm, res.data.data)
    dialogVisible.value = true
  } catch (error) {
    console.error('获取角色详情失败', error)
    ElMessage.error('获取角色详情失败')
  }
}

// 删除角色
const handleDelete = async (id) => {
  try {
    await deleteRole(id)
    ElMessage.success('删除成功')
    fetchRoleList()
  } catch (error) {
    console.error('删除角色失败', error)
    ElMessage.error('删除角色失败')
  }
}

// 分配权限
const handleAssignPermission = async (row) => {
  currentRoleId.value = row.id
  try {
    // 获取权限树
    const treeRes = await getPermissionTree()
    permissionTree.value = treeRes.data.data || []
    console.log('权限树数据:', permissionTree.value)

    // 获取角色已有权限
    const permRes = await getRolePermissions(row.id)
    const permissions = permRes.data.data || []
    console.log('角色已有权限:', permissions)

    // 提取权限ID列表用于设置选中状态
    const permissionIds = permissions.map((item) => item.id)
    console.log('设置选中的权限ID:', permissionIds)

    // 等待DOM更新后设置选中状态
    setTimeout(() => {
      permissionTreeRef.value.setCheckedKeys(permissionIds)

      // 验证选中状态
      const actualChecked = permissionTreeRef.value.getCheckedKeys()
      console.log('实际选中的权限ID:', actualChecked)
    }, 100)

    permissionDialogVisible.value = true
  } catch (error) {
    console.error('获取权限数据失败', error)
    ElMessage.error('获取权限数据失败')
  }
}

// 提交权限分配
const submitPermission = async () => {
  if (!currentRoleId.value) return

  try {
    // 获取选中的权限ID（只获取完全选中的节点，不包括半选中的父节点）
    const checkedKeys = permissionTreeRef.value.getCheckedKeys(true)

    // 打印日志，便于调试
    console.log('选中的权限ID:', checkedKeys)

    // 调用API保存权限
    await assignRolePermissions(currentRoleId.value, checkedKeys)

    ElMessage({
      message: '权限分配成功，相关用户需要重新登录才能生效',
      type: 'success',
      duration: 5000
    })
    permissionDialogVisible.value = false

    // 添加延迟，确保后端处理完成
    setTimeout(() => {
      // 刷新角色列表，确保数据最新
      fetchRoleList()
    }, 500)
  } catch (error) {
    console.error('权限分配失败', error)
    ElMessage.error('权限分配失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!roleFormRef.value) return

  await roleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await updateRole(roleForm)
          ElMessage.success('更新成功')
        } else {
          await addRole(roleForm)
          ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        fetchRoleList()
      } catch (error) {
        console.error('保存角色失败', error)
        ElMessage.error('保存角色失败')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }
  Object.assign(roleForm, {
    id: null,
    roleName: '',
    roleCode: '',
    description: '',
    status: 1
  })
}
</script>

<style scoped>
.role-manage-container {
  padding: 20px;
}

.header-actions {
  margin-bottom: 20px;
}
</style>
